//
//  BSRequest.m
//  PhotographyStudi
//
//  Created by 叶一枫 on 2017/5/22.
//  Copyright © 2017年 叶一枫. All rights reserved.
//

#import "BSRequest.h"

@implementation BSRequest

+(BSRequest*)shareBSRequest{
    
    static BSRequest *bsRequest = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        bsRequest = [[self alloc]init];
    });
    return bsRequest;
}


-(void)postMessageWithUrl:(NSString *)url parameter:(NSDictionary *)parameter requestBlock:(BSBlock)requestBlock{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //接受数据的返回类型
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json", @"text/javascript",@"text/plain", nil];
    //设置超时
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 20.f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    NSString*pathUrl = [NSString stringWithFormat:@"%@/%@",APP_SERVER_URL,url];
    
    [manager POST:pathUrl parameters:parameter progress:^(NSProgress * _Nonnull uploadProgress) {
        //监控网络请求进度
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *html = responseObject;
        NSData* data=[html dataUsingEncoding:NSUTF8StringEncoding];
        
        //输出
        NSLog(@"\n\n==========================成功=============================\n==========================成功=============================\n\n\n url=%@ \n dic=%@ \n\n 返回：%@",url,parameter,[NSJSONSerialization JSONObjectWithData:data options:0 error:nil]);
        
        if ([[NSJSONSerialization JSONObjectWithData:data options:0 error:nil] isKindOfClass:[NSArray class]]) {
            BSRequestMode *model = [[BSRequestMode alloc]init];
            model.modelArr = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            requestBlock(model);
        }else if ([[NSJSONSerialization JSONObjectWithData:data options:0 error:nil] isKindOfClass:[NSDictionary class]]){
            BSRequestMode *model = [[BSRequestMode alloc]init];
            model.modelDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            requestBlock(model);
        }else{
            BSRequestMode *model = [[BSRequestMode alloc]init];
            model.modelError = [NSError errorWithDomain:@"接收不到返回值" code:888 userInfo:@{@"errorStr":@"可能原因：接口错误，返回为空"}];
            requestBlock(model);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"\n\nurl=%@\ndic=%@\n\nerror：%@",url,parameter,error);
    }];
}



-(void)postFileWithUrl:(NSString *)url parameter:(NSDictionary *)parameter fileDic:(NSDictionary *)fileDic block:(BSBlock)requestBlock{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //formData: 专门用于拼接需要上传的数据,在此位置生成一个要上传的数据体
    [manager POST:url parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        // 在网络开发中，上传文件时，是文件不允许被覆盖，文件重名
        // 要解决此问题，
        // 可以在上传时使用当前的系统事件作为文件名
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        // 设置时间格式
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
        
        //上传
        /*
         此方法参数
         1. 要上传的[二进制数据]
         2. 对应网站上[upload.php中]处理文件的[字段"file"]
         3. 要保存在服务器上的[文件名]
         4. 上传文件的[mimeType]
         */
        [formData appendPartWithFileData:[fileDic objectForKey:@"fileData"] name:@"file" fileName:fileName mimeType:@"image/png"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        //上传进度
        // @property int64_t totalUnitCount;     需要下载文件的总大小
        // @property int64_t completedUnitCount; 当前已经下载的大小
        // 给Progress添加监听 KVO
        // 回到主队列刷新UI,用户自定义的进度条
        dispatch_async(dispatch_get_main_queue(), ^{

        });
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSString *html = responseObject;
        NSData* data=[html dataUsingEncoding:NSUTF8StringEncoding];
        //输出
        NSLog(@"\n\n==========================成功=============================\n==========================成功=============================\n\n\n url=%@ \n dic=%@ \n\n 返回：%@",url,parameter,[NSJSONSerialization JSONObjectWithData:data options:0 error:nil]);
        
        if ([[NSJSONSerialization JSONObjectWithData:data options:0 error:nil] isKindOfClass:[NSArray class]]) {
            BSRequestMode *model = [[BSRequestMode alloc]init];
            model.modelArr = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            requestBlock(model);
        }else if ([[NSJSONSerialization JSONObjectWithData:data options:0 error:nil] isKindOfClass:[NSDictionary class]]){
            BSRequestMode *model = [[BSRequestMode alloc]init];
            model.modelDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            requestBlock(model);
        }else{
            BSRequestMode *model = [[BSRequestMode alloc]init];
            model.modelError = [NSError errorWithDomain:@"接收不到返回值" code:888 userInfo:@{@"errorStr":@"可能原因：接口错误，返回为空"}];
            requestBlock(model);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"\n\nurl=%@\ndic=%@\n\nerror：%@",url,parameter,error);

    }];
}



-(void)getMessageWithUrl:(NSString *)url parameter:(NSDictionary *)parameter block:(BSBlock)requestBlock{
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager GET:url parameters:parameter progress:^(NSProgress * _Nonnull downloadProgress) {
        
    }
         success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
             
             NSLog(@"这里打印请求成功要做的事");
             
         }
     
         failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull   error) {
             
             NSLog(@"%@",error);  //这里打印错误信息
             
         }];
}

-(void)getFileWithUrl:(NSString *)url parameter:(NSDictionary *)parameter fileDic:(NSDictionary *)fileDic block:(BSBlock)requestBlock{
    
    
}

-(void)downLoadFile:(NSString *)url parameter:(NSDictionary *)parameter fileDic:(NSDictionary *)fileDic{


}



@end
